// var amapFile = require('../../../utils/amap-wx.js')
// var amap = new amapFile.AMapWX({key: 'c9f1b5ebbb57dfbd7c46a063d843a4a3'})
var markersData = []
import { getAmap, getGeocoder } from '../../api/pay'
import { getLocation, toast } from '../../../utils/util'
const staticKey = 'OKZBZ-LWF65-MSSIU-ILBD7-RQHU2-W6FQG'
Page({
    data: {
        markers: [],
        latitude: '',
        longitude: '',
        textData: {},
        circle: [{
            latitude: 0,
            longitude: 0,
            radius: 300,
            fillColor: '#FF7E6833',
            color: '#FF7E6833',
        }],
        poi: [],
        current: {
            name: '',
            describe: ''
        },
        region: [],
        ranges: [80, 100, 300, 500, 800, 1000],
        range: 500,
        isComponent: false,
        value: ''
    },
    makertap: function (e) {
        var id = e.markerId
        var that = this
        that.showMarkerInfo(markersData, id)
        that.changeMarkerColor(markersData, id)
    },
    onLoad: function (options) {
        console.log(this.data.range, 'option.lenoption.lenoption.len')
        if (options.len) {
            this.setData({
                range: options.len*1
            })
        }
        // 初始化地图
        getLocation().then(res=>{
            // this.setMarker(res.longitude, res.latitude, true)
            console.log(res, '初始化地图信息')
            // this.setMarker(res.longitude, res.latitude, true)
            this.getGeocoder(res.latitude, res.longitude)
        })
        this.setData({
            isComponent: !!options.isComponent
        })
    },
    // 地图点击
    maptap(event) {
        console.log(event, '地图点击')
        this.getGeocoder(event.detail.latitude, event.detail.longitude)
        // this.setMarker(event.detail.longitude, event.detail.latitude, 1)
    },
    // poi点击选择
    async selectPoi(event) {
        console.log(event, '点击啦')
        this.setData({
            ['current.name']: event.currentTarget.dataset.name,
            ['current.describe']: event.currentTarget.dataset.address,
        })
        let location = event.currentTarget.dataset.location
        if(!event.currentTarget.dataset.location) {
            toast('请选择精准位置')
            return
        }
        this.getGeocoderc(event.currentTarget.dataset.location.lat, event.currentTarget.dataset.location.lng, 1)
        // await this.setMarker(event.currentTarget.dataset.location.lng,event.currentTarget.dataset.location.lat)

        // await this.setMarker(...event.currentTarget.dataset.location.split(','))
        // setTimeout(()=>{
        //     this.setData({
        //         ['current.name']: event.currentTarget.dataset.name,
        //         ['current.describe']: event.currentTarget.dataset.address,
        //     },()=>{
        //         console.log(this.data.current.name,this.data.current.describe)
        //     })
        // },500)

    },
    async getLatlongByAddress(address) {
        return new Promise(async(resolve) => {
            const result = await getGeocoder({
                address,
                key: staticKey,
            })
            if(result?.result?.location) {
                resolve(result.result.location)
            }
        })
    },

    // 逆地理解析位置 拿到周边信息
    async getGeocoder(latitude, longitude, index) {
        // https://apis.map.qq.com/ws/geocoder/v1/?location=39.984154,116.307490&key=OB4BZ-D4W3U-B7VVO-4PJWW-6TKDJ-WPB77&get_poi=1
        const result = await getGeocoder({
            location: latitude+','+longitude,
            key: staticKey,
            get_poi: 1,
            poi_options: 'policy=2'
        })
        this.setData({
            latitude: latitude,
            longitude: longitude,
            ['circle[0].latitude']: latitude,
            ['circle[0].longitude']: longitude,

            ['current.name']: result.result.formatted_addresses.recommend,
            ['current.describe']: result.result.address,
            ['region[0]']: result.result.ad_info.province || '',
            ['region[1]']: result.result.ad_info.city || '', // res.tips[0].address,
            ['region[2]']: result.result.ad_info.district || '', // res.tips[0].address,
            ['markers[0]']: {
                latitude: latitude,
                longitude: longitude,
                iconPath: '../../assets/img/clock-address/position.png',
                width: 28,
                height: 28
            },
            poi: result.result.pois.slice(index ? 2 : 1)
        })
        console.log(this.data.current, 'current')
        console.log(result, 'result')
    },

    async getGeocoderc(latitude, longitude, index) {
        // https://apis.map.qq.com/ws/geocoder/v1/?location=39.984154,116.307490&key=OB4BZ-D4W3U-B7VVO-4PJWW-6TKDJ-WPB77&get_poi=1
        const result = await getGeocoder({
            location: latitude+','+longitude,
            key: staticKey,
            get_poi: 1,
            poi_options: 'policy=2'
        })
        this.setData({
            latitude: latitude,
            longitude: longitude,
            ['circle[0].latitude']: latitude,
            ['circle[0].longitude']: longitude,
            ['region[0]']: result.result.ad_info.province || '',
            ['region[1]']: result.result.ad_info.city || '', // res.tips[0].address,
            ['region[2]']: result.result.ad_info.district || '', // res.tips[0].address,
            ['markers[0]']: {
                latitude: latitude,
                longitude: longitude,
                iconPath: '../../assets/img/clock-address/position.png',
                width: 28,
                height: 28
            },
            poi: result.result.pois.slice(index ? 2 : 1)
        })
        console.log(this.data.current, 'current')
        console.log(result, 'result')
    },
    // 设置点位置并自动加载周边地点
    setMarker(longitude, latitude, init = false) {
        console.log(longitude, latitude, '点击地图位置')
        this.setData({
            latitude: latitude,
            longitude: longitude,
            ['circle[0].latitude']: latitude,
            ['circle[0].longitude']: longitude,
            ['markers[0]']: {
                latitude: latitude,
                longitude: longitude,
                iconPath: '../../assets/img/clock-address/position.png',
                width: 28,
                height: 28
            }
        })
        this.getPoi(longitude, latitude, init, this.data.value)
    },
    // 获取周边地点信息
    getPoi(longitude, latitude, init = false, value='') {
        console.log(longitude + ',' + latitude)
        // https://cloudcode.51zidan.com/api/amap?location=116.490377,39.975437&keywords=%E6%B1%9F%E5%8D%97&type=inputtips 
        // amap.getRegeo  iconPath: '../../assets/img/clock-address/position.png',
        getAmap({
            // keywords: value || '人力资源' ,
            keyword: value,
            type: 'inputtips',
            // location: longitude + ',' + latitude,
            boundary: `nearby(${latitude + ',' + longitude},1000)`,
            page_size: 10,
            page_index: 1,
            key: staticKey
        }).then(res=>{
            console.log(res, 'resres')
            // res.tips = res.tips.filter(item=>typeof item.location === 'string')
            // const district = res.tips[0].district.split(/[省市区县]/)
            // console.log(district)
            if (!res.data.length) {
                this.setData({
                    poi: []
                })
                return
            }

            this.setData({
                ['current.name']: res.data[0].title,
                ['current.describe']: res.data[0].address,
                ['region[0]']: res.data[0].ad_info.province || '',
                ['region[1]']: res.data[0].ad_info.city || '', // res.tips[0].address,
                ['region[2]']: res.data[0].ad_info.district || '', // res.tips[0].address,
                ['latitude']: res.data[0].location.lat,
                ['longitude']: res.data[0].location.lng,
                ['markers[0]']: {
                    latitude: res.data[0].location.lat,
                    longitude: res.data[0].location.lng,
                    iconPath: '../../assets/img/clock-address/position.png',
                    width: 28,
                    height: 28
                },
                ['circle[0].latitude']: res.data[0].location.lat,
                ['circle[0].longitude']: res.data[0].location.lng
            })
            console.log(this.data.current, 'current')
            this.setData({
                poi: res.data.slice(1)
            })
        })
    },
    bindRegionChange(event) {
        this.setData({
            region: event.detail.value
        })
        console.log(1234, this.data.region)
        
    },
    bindRangeChange(event) {
        const range = this.data.ranges[event.detail.value]
        this.setData({
            range,
            ['circle[0].radius']: Number(range)
        })
    },
    async searchPoi(event) {
        console.log(event, '领')
        const keyword = this.data.region.join('') + event.detail.value
        this.setData({
            value: event.detail.value
        })
        const location = await this.getLatlongByAddress(keyword)
        this.getPoi(location.lng, location.lat, false, keyword)
        // amap.getInputtips({
        //     city: this.data.region,
        //     keywords: keyword,
        //     success: (res) => {
        //         this.setData({
        //             poi: res.tips
        //         })
        //     }
        // })
    },
    // 提交
    onSubmit() {
        const pages = getCurrentPages()
        if(this.data.isComponent) {
            console.log('进入这里11111')
            pages[pages.length-2].selectComponent('#add-project').selectAddressComplete({
                radius: this.data.circle[0].radius,
                current: this.data.current,
                latitude: this.data.latitude,
                longitude: this.data.longitude
            })
        }
        else{
            console.log('进入这里')
            pages[pages.length-2].selectAddressComplete({
                radius: this.data.circle[0].radius,
                current: this.data.current,
                latitude: this.data.latitude,
                longitude: this.data.longitude
            })
        }

        wx.navigateBack()
    }

})